import ScrollBarLayout from '@/components/ScrollBarLayout';
import { Badge, Col, Empty, Row } from 'antd';
import React, { useContext, useEffect, useRef, useState } from 'react';
import { ContractCountContext } from '../common';
import { handleSum, handleSumStr, stateCountContract } from '../mconfig';
//引入echarts主模块
import * as echarts from 'echarts';
// 引入柱状图
import 'echarts/lib/chart/bar';
// 引入饼状图
import 'echarts/lib/chart/pie';
// 引入标题和提示框
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import ReactDOM from 'react-dom';

let allStateView: any; //状态收付款统计
let payStateView: any; //状态付款统计
let putStateView: any; //状态收款统计

export const StateCountEchartsView: React.FC<ContractAllCountAPI.IStateCountEchartsView> = ({ contractStateInfo }) => {
  /** 引入上下文 */
  const { echartsDetailInfo, styleFixCls } = useContext(ContractCountContext);

  let allStateCountRef: any = useRef(); //状态收付款统计Ref
  let payStateCountRef: any = useRef(); //状态付款统计
  let putStateCountRef: any = useRef(); //状态收款统计

  /** 保存收付款数量和金额 */
  const [payPutNumSum, setPayPutNumSum] = useState<Record<string, any>>({
    payNumAll: 0,
    paySumAll: 0,
    putNumAll: 0,
    putSumAll: 0,
  });

  /** 初始化 */
  useEffect(() => {
    if (echartsDetailInfo && JSON.stringify(echartsDetailInfo) != '{}' && contractStateInfo && JSON?.stringify(contractStateInfo) != '{}') {
      /** 获取处理好的数据 */
      const {
        topStateNameList,
        topStatePayNums,
        topStatePaySums,
        topStatePutNums,
        topStatePutSums,
        payNumsInfoList,
        paySumsInfoList,
        putNumsInfoList,
        putSumsInfoList,
        payNumAll,
        paySumAll,
        putNumAll,
        putSumAll,
      } = stateCountContract(echartsDetailInfo, contractStateInfo);

      setPayPutNumSum({
        payNumAll,
        paySumAll,
        putNumAll,
        putSumAll,
      });

      /** 渲染合同状态汇总统计 */
      allStateBarRender({
        stateNameList: topStateNameList,
        statePayNums: topStatePayNums,
        statePaySums: topStatePaySums,
        statePutNums: topStatePutNums,
        statePutSums: topStatePutSums,
      });

      /** 合同付款 */
      putPayStateBarRender(
        {
          stateNameList: topStateNameList,
          stateNumList: payNumsInfoList,
          stateSumList: paySumsInfoList,
        },
        false,
      );

      /** 合同收款 */
      putPayStateBarRender(
        {
          stateNameList: topStateNameList,
          stateNumList: putNumsInfoList,
          stateSumList: putSumsInfoList,
        },
        true,
      );
    } else {
      setPayPutNumSum({
        payNumAll: 0,
        paySumAll: 0,
        putNumAll: 0,
        putSumAll: 0,
      });
    }
  }, [echartsDetailInfo, contractStateInfo]);

  /**
   * 处理柱状图鼠标移入气泡
   * @param params
   * @returns
   */
  const renderTooltip = (params: Record<string, any>[]) => {
    let tipStr: string = `${params?.[0]?.name}`;
    params?.forEach((item: any) => {
      tipStr += ` 
        <br />
        ${item?.marker}${item?.seriesName}：${item?.seriesName?.includes('数量') ? item?.value + ' 个' : handleSumStr(Number(item?.value))}
        `;
    });
    return tipStr;
  };

  /** 合同状态汇总统计 */
  const allStateBarRender = (dataInfo: Record<string, any>) => {
    if (allStateView != null && allStateView != '' && allStateView != undefined) {
      allStateView?.dispose();
    }

    const { stateNameList, statePayNums, statePaySums, statePutNums, statePutSums } = dataInfo;

    // 柱状的总统计图
    const option: any = {
      title: {
        text: '合同状态汇总统计',
        left: 'center',
      },
      grid: {
        left: '5%',
        bottom: '15%',
        top: '22%',
        right: '8%',
      },
      tooltip: {
        trigger: 'axis',
        // axisPointer: {
        //   type: 'cross',
        // },
        axisPointer: {
          type: 'shadow',
        },
        formatter: (params) => {
          return renderTooltip(params);
        },
      },
      legend: {
        data: ['付款数量', '付款金额', '收款数量', '收款金额'],
        padding: [30, 5],
      },
      toolbox: {
        show: true,
        feature: {
          magicType: {
            mark: { show: true },
            show: true,
            type: ['line', 'bar'],
            title: {
              line: '',
              bar: '',
            },
          },
        },
        right: '4%',
        padding: [30, 5],
      },
      calculable: true,
      xAxis: [
        {
          type: 'category',
          data: stateNameList,
          // name: stepTypeValue,
          axisLabel: {
            interval: 0,
            rotate: 40,
            formatter: (value: any) => {
              const newValue: string = value?.length > 6 ? `${value?.slice(0, 5)}...` : value;
              return value != 'null' ? newValue : '--';
            },
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          name: '数量/个',
          position: 'left',
          alignTicks: true,
          axisLine: {
            show: true,
          },
          axisLabel: {
            formatter: (value) => {
              return Number.isInteger(value) ? value : '';
            },
          },
        },
        {
          type: 'value',
          name: '金额/元',
          position: 'right',
          alignTicks: true,
          axisLine: {
            show: true,
          },
        },
      ],
      series: [
        {
          name: '付款数量',
          type: 'bar',
          data: statePayNums,
          yAxisIndex: 0,
          label: {
            show: true,
            position: 'top',
          },
        },
        {
          name: '付款金额',
          type: 'bar',
          data: statePaySums,
          yAxisIndex: 1,
          label: {
            show: true,
            position: 'top',
          },
        },
        {
          name: '收款数量',
          type: 'bar',
          data: statePutNums,
          yAxisIndex: 0,
          label: {
            show: true,
            position: 'top',
          },
        },
        {
          name: '收款金额',
          type: 'bar',
          data: statePutSums,
          yAxisIndex: 1,
          label: {
            show: true,
            position: 'top',
          },
        },
      ],
    };

    /** 合同数量汇总 */
    const allStateViewDiv: any = ReactDOM.findDOMNode(allStateCountRef?.current);
    allStateView = echarts.init(allStateViewDiv);
    allStateView.setOption(option, true);
  };

  /** 收付款饼图 */
  const putPayStateBarRender = (dataInfo: Record<string, any>, payOrPutBool: boolean) => {
    if (payOrPutBool) {
      //收款
      if (putStateView != null && putStateView != '' && putStateView != undefined) {
        putStateView?.dispose();
      }
    } else {
      //付款
      if (payStateView != null && payStateView != '' && payStateView != undefined) {
        payStateView?.dispose();
      }
    }

    const { stateNameList, stateNumList, stateSumList } = dataInfo;
    const option: Record<string, any> = {
      title: {
        text: payOrPutBool ? '合同收款状态统计' : '合同付款状态统计',
        x: 'center',
      },
      tooltip: {
        trigger: 'item',
        formatter: (params) => {
          let payload: Record<string, any> = {};
          if (params.seriesName == '数量') {
            payload = stateSumList?.find((itemSum: any) => itemSum?.name == params?.name);
            return (
              params.name + '<br/>' + params.marker + params.seriesName + '：' + params.value + ` 个<br/>${params.marker}金额：` + handleSumStr(payload?.value)
            );
          } else {
            payload = stateNumList?.find((itemSum: any) => itemSum?.name == params?.name);
            return (
              params.name +
              '<br/>' +
              params.marker +
              params.seriesName +
              '：' +
              handleSumStr(params?.value) +
              `<br/>${params.marker}数量：` +
              payload?.value +
              ` 个`
            );
          }
        },
      },
      legend: {
        data: stateNameList,
        orient: 'vertical',
        left: 'left',
      },
      series: [
        {
          name: '数量',
          type: 'pie',
          selectedMode: 'single',
          radius: [0, '30%'],
          top: '8%',
          label: {
            position: 'inner',
            fontSize: 14,
            formatter: `{c}`,
          },
          labelLine: {
            show: false,
          },
          data: stateNumList,
        },
        {
          name: '金额',
          type: 'pie',
          radius: ['45%', '60%'],
          top: '8%',
          labelLine: {
            length: 30,
          },
          data: stateSumList,
          label: {
            formatter: `{c}`,
          },
        },
      ],
    };

    if (payOrPutBool) {
      //收款
      const putStateViewDiv: any = ReactDOM.findDOMNode(putStateCountRef?.current);
      putStateView = echarts.init(putStateViewDiv);
      putStateView.setOption(option, true);
    } else {
      //付款
      const payStateViewDiv: any = ReactDOM.findDOMNode(payStateCountRef?.current);
      payStateView = echarts.init(payStateViewDiv);
      payStateView.setOption(option, true);
    }
  };

  /** 返回徽标 */
  const renderBadgeText = (numValue: number, sumValue: number) => {
    return (
      <span>
        <div>
          <span>
            总数量：
            <span style={{ fontSize: 16, color: '#ff4d4f', fontWeight: 600 }}>{numValue || 0}</span>
            &nbsp;个
          </span>
        </div>
        <div>
          <span>
            总金额：
            {handleSum(sumValue)}
          </span>
        </div>
      </span>
    );
  };

  return (
    <div className={`${styleFixCls}allCountDiv-bodyBox`}>
      <ScrollBarLayout style={{ padding: '0px' }}>
        <Row>
          <Col span={12} style={{ paddingRight: 2 }}>
            <Badge.Ribbon
              text={renderBadgeText(payPutNumSum?.payNumAll, payPutNumSum?.paySumAll)}
              color="#ececec"
              className={`${styleFixCls}allCountDiv-bodyBox-BadgeDiv`}
            >
              <div className={`${styleFixCls}allCountDiv-bodyBox-colDiv`}>
                {echartsDetailInfo && JSON.stringify(echartsDetailInfo) != '{}' ? (
                  <div className={`${styleFixCls}allCountDiv-bodyBox-echartsDiv`} ref={payStateCountRef} />
                ) : (
                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无【合同付款状态汇总统计】数据" />
                )}
              </div>
            </Badge.Ribbon>
          </Col>
          <Col span={12} style={{ paddingLeft: 2 }}>
            <Badge.Ribbon
              text={renderBadgeText(payPutNumSum?.putNumAll, payPutNumSum?.putSumAll)}
              color="#ececec"
              className={`${styleFixCls}allCountDiv-bodyBox-BadgeDiv`}
            >
              <div className={`${styleFixCls}allCountDiv-bodyBox-colDiv`}>
                {echartsDetailInfo && JSON.stringify(echartsDetailInfo) != '{}' ? (
                  <div className={`${styleFixCls}allCountDiv-bodyBox-echartsDiv`} ref={putStateCountRef} />
                ) : (
                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无【合同收款状态汇总统计】数据" />
                )}
              </div>
            </Badge.Ribbon>
          </Col>
          <Col span={24} style={{ paddingTop: 4 }}>
            <div className={`${styleFixCls}allCountDiv-bodyBox-colDiv`}>
              {echartsDetailInfo && JSON.stringify(echartsDetailInfo) != '{}' ? (
                <div className={`${styleFixCls}allCountDiv-bodyBox-echartsDiv`} ref={allStateCountRef} />
              ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无【合同状态汇总统计】数据" />
              )}
            </div>
          </Col>
        </Row>
      </ScrollBarLayout>
    </div>
  );
};
